package com.flaremars.picker.fragments;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.cloud.CloudListener;
import com.baidu.mapapi.cloud.CloudManager;
import com.baidu.mapapi.cloud.CloudPoiInfo;
import com.baidu.mapapi.cloud.CloudSearchResult;
import com.baidu.mapapi.cloud.DetailSearchResult;
import com.baidu.mapapi.cloud.NearbySearchInfo;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.flaremars.picker.R;
import com.flaremars.picker.bean.Coordinate;
import com.flaremars.picker.constants.ProjectConstants;
import com.flaremars.picker.utils.CoordinateUtils;

import java.util.List;

/**
 * @author FlareMars
 * 雷达界面
 */
public class RadarFragment extends Fragment implements CloudListener, BDLocationListener {

    private static final int MINE_POS_UID = 0;

    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient locationClient;
    private Coordinate curPos = new Coordinate();
    private int searchRadius = 300;

    public RadarFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        locationClient = new LocationClient(getActivity().getApplicationContext());
        initLocation();
        return inflater.inflate(R.layout.fragment_radar, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        CloudManager.getInstance().init(this);
        mapView = (MapView) view.findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();
        mapView.showZoomControls(false);
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getExtraInfo().getInt("id") == MINE_POS_UID) {
                    handleMineMarkerClick(marker);
                } else {
                    handleOtherMarkerClick(marker);
                }
                return true;
            }
        });

    }

    //处理当前位置点击事件
    private void handleMineMarkerClick(Marker marker) {

        Toast.makeText(getContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
    }

    //处理其他目标地点点击事件
    private void handleOtherMarkerClick(Marker marker) {
        Toast.makeText(getContext(), marker.getTitle() + " " + marker.getExtraInfo().getInt("id") + "\n" +
                "与你距离:" +
                CoordinateUtils.INSTANCE.distance(
                        curPos, new Coordinate(marker.getPosition().longitude, marker.getPosition().latitude)) +
                "米", Toast.LENGTH_SHORT).show();
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        locationClient.registerLocationListener(this);
        locationClient.setLocOption(option);
    }

    //进行云检索 检索附近的目标地点
    private void nearbySearch(Double lon,Double lat) {
        curPos.setLat(lat);
        curPos.setLon(lon);
        NearbySearchInfo info = new NearbySearchInfo();
        info.ak = ProjectConstants.BAIDU_MAP_SERVER_AK;
        info.geoTableId = ProjectConstants.NEARBY_TARGET_TABLE_ID;
        info.radius = searchRadius;
        info.location = lon + "," + lat;
        CloudManager.getInstance().nearbySearch(info);

    }

    public void onGetDetailSearchResult(DetailSearchResult result, int error) {
        if (result != null) {
            if (result.poiInfo != null) {
                Toast.makeText(getContext(), result.poiInfo.title,
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(),
                        "status:" + result.status, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //云检索结果回调
    public void onGetSearchResult(CloudSearchResult result, int error) {
        baiduMap.clear();

        BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding_mine);
        LatLng ll;
        LatLngBounds.Builder builder = new LatLngBounds.Builder();

        //添加当前位置
        ll = new LatLng(curPos.getLat(), curPos.getLon());
        Bundle idBundle = new Bundle();
        idBundle.putInt("id", MINE_POS_UID);
        OverlayOptions oo = new MarkerOptions().icon(bd).position(ll).title("当前你所在位置").extraInfo(idBundle);
        baiduMap.addOverlay(oo);
        builder.include(ll);

        if (result != null && result.poiList != null
                && result.poiList.size() > 0) {
            Log.d("tag", "onGetSearchResult, result length: " + result.poiList.size());
            bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
            for (CloudPoiInfo info : result.poiList) {
                Log.d("tag",info.title + " " + info.uid);
                ll = new LatLng(info.latitude, info.longitude);
                idBundle = new Bundle();
                idBundle.putInt("id",info.uid);
                oo = new MarkerOptions().icon(bd).position(ll).title(info.title).extraInfo(idBundle);
                baiduMap.addOverlay(oo);
                builder.include(ll);
            }
        }

        LatLngBounds bounds = builder.build();
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
        baiduMap.animateMapStatus(u);
    }

    //定位结果回调
    @Override
    public void onReceiveLocation(BDLocation location) {
        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ");
        sb.append(location.getTime());
        sb.append("\nerror code : ");
        sb.append(location.getLocType());
        sb.append("\nlatitude : ");
        sb.append(location.getLatitude());
        sb.append("\nlontitude : ");
        sb.append(location.getLongitude());
        sb.append("\nradius : ");
        sb.append(location.getRadius());

        Log.i("BaiduLocationApiDem", sb.toString());

        nearbySearch(location.getLongitude(), location.getLatitude());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        CloudManager.getInstance().destroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        locationClient.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        locationClient.stop();
    }

    private void getDeatilInfo(StringBuffer sb,BDLocation location) {
        if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
            sb.append("\nspeed : ");
            sb.append(location.getSpeed());// 单位：公里每小时
            sb.append("\nsatellite : ");
            sb.append(location.getSatelliteNumber());
            sb.append("\nheight : ");
            sb.append(location.getAltitude());// 单位：米
            sb.append("\ndirection : ");
            sb.append(location.getDirection());// 单位度
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            sb.append("\ndescribe : ");
            sb.append("gps定位成功");

        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            //运营商信息
            sb.append("\noperationers : ");
            sb.append(location.getOperators());
            sb.append("\ndescribe : ");
            sb.append("网络定位成功");
        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
            sb.append("\ndescribe : ");
            sb.append("离线定位成功，离线定位结果也是有效的");
        } else if (location.getLocType() == BDLocation.TypeServerError) {
            sb.append("\ndescribe : ");
            sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
            sb.append("\ndescribe : ");
            sb.append("网络不同导致定位失败，请检查网络是否通畅");
        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
            sb.append("\ndescribe : ");
            sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
        }
        sb.append("\nlocationdescribe : ");
        sb.append(location.getLocationDescribe());// 位置语义化信息
        List<Poi> list = location.getPoiList();// POI数据
        if (list != null) {
            sb.append("\npoilist size = : ");
            sb.append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ");
                sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
            }
        }
    }
}
